package com.soxing.braindata.service.stat;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.soxing.braindata.dao.domain.request.ResearchSearchRequest;
import com.soxing.braindata.dao.domain.vo.TinyResearch;
import com.soxing.braindata.dao.entity.Experiment;
import com.soxing.braindata.dao.entity.StatItemResult;
import com.soxing.braindata.dao.entity.Testee;
import com.soxing.braindata.dao.entity.TesteeExperiment;
import com.soxing.braindata.dao.service.IExperimentService;
import com.soxing.braindata.dao.service.IStatItemResultService;
import com.soxing.braindata.dao.service.ITesteeExperimentService;
import com.soxing.braindata.dao.service.ITesteeService;
import com.soxing.braindata.domain.stat.CollectEntity;
import com.soxing.braindata.domain.stat.FinishEntity;
import com.soxing.braindata.domain.stat.YearEntity;
import com.soxing.braindata.domain.vo.VpInfoVo;
import com.soxing.braindata.service.manager.IResearchManager;
import com.soxing.common.utils.response.MyPage;
import com.soxing.common.utils.response.WebResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@Slf4j
@Service("finishBarServiceImpl")
public class FinishBarServiceImpl implements IStatService{

    @Resource
    private IResearchManager researchManager;

    @Resource
    private IStatItemResultService statItemResultService;

    @Resource
    private ITesteeExperimentService testeeExperimentService;

    @Resource
    private ITesteeService testeeService;


    @Resource
    private IExperimentService experimentService;

    @Override
    public void stat(Date beginTime, Date endTime, Integer period) {
        ResearchSearchRequest request = new ResearchSearchRequest();
        List<Integer> stateList = Lists.newArrayList();
        stateList.add(1);
        stateList.add(3);
        request.setStateList(stateList);
        request.setPageSize(10000);
        WebResponse<MyPage<TinyResearch>> response = researchManager.search(request);
        List<TinyResearch> records = response.getData().getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return;
        }
        Set<String> subjectPkIdSet = records.stream().map(TinyResearch::getSubjectPkId).collect(Collectors.toSet());
        //上面这一段代码都是为了获得一个研究码的集合
        //List<Testee> testeeList = testeeService.list(new LambdaQueryWrapper<Testee>().in(Testee::getSubjectPkId, subjectPkIdSet));
        //List<TesteeExperiment> testeeExperimentList = testeeExperimentService.list(new LambdaQueryWrapper<TesteeExperiment>().in(TesteeExperiment::getSubjectPkId, subjectPkIdSet));
        //还需要一个包含全部任务的列表，然后再分一下组变成hashmap 这样应该就是可以的了
        List<Experiment> ExperimentList = experimentService.list(new LambdaQueryWrapper<Experiment>().in(Experiment::getSubjectPkId, subjectPkIdSet));
        if (CollectionUtils.isEmpty(ExperimentList)) {
            return;
        }
        Map<String,Long> ExperimentMap = ExperimentList.stream().collect(Collectors.groupingBy(Experiment::getSubjectPkId,Collectors.counting()));

        //这里主要就是遍历被试列表呀
        List<Testee> testeeList = testeeService.list(new LambdaQueryWrapper<Testee>().in(Testee::getSubjectPkId, subjectPkIdSet));
        if (CollectionUtils.isEmpty(testeeList)) {
            return;
        }

        Map<String, List<Testee>> subjectPkId2TesteeListMap = new HashMap<>();
        for (Testee testee : testeeList) {
            String subjectPkId = testee.getSubjectPkId();
            List<Testee> testeeList1 = subjectPkId2TesteeListMap.get(subjectPkId);
            if (testeeList1 == null) {
                testeeList1 = new ArrayList<>();
                subjectPkId2TesteeListMap.put(subjectPkId, testeeList1);
            }
            testeeList1.add(testee);
        }



        subjectPkId2TesteeListMap.forEach((rcode, tList) -> {

            Map<String,List<Testee>> sitePkIdTesteeListMap = tList.stream().collect(Collectors.groupingBy(Testee::getSitePkId));

            if(!ExperimentMap.containsKey(rcode))
            {
                return;//在foreach中return相当于continue;
            }


            List<VpInfoVo> vpList = null;
            for(TinyResearch research:records)
            {
                if(research.getSubjectPkId().equals(rcode))
                {

                    vpList =  com.alibaba.fastjson.JSONArray.parseArray(research.getVpInfo(),VpInfoVo.class);


                }
            }

            if(vpList==null||vpList.isEmpty())
            {
                return;
            }







            long num = ExperimentMap.get(rcode)*vpList.size();//总共需要采集量是采集阶段数量*任务数量



            sitePkIdTesteeListMap.forEach(
                    (sitePkId, SList) -> {
                        long complete = 0;
                        long incomplete = 0;
                        for(Testee testee:SList)
                        {
                            List<TesteeExperiment> testeeExperimentList= testeeExperimentService.list(new LambdaQueryWrapper<TesteeExperiment>().in(TesteeExperiment::getTesteeNo,testee.getTesteeNo()));
                            //Map<Integer,List<TesteeExperiment>> record = testeeExperimentList.stream().collect(Collectors.groupingBy(TesteeExperiment::getExperimentId));
                            //map<任务id，set<vp>>
                            Map<Integer,Set<String>> record1 = testeeExperimentList.stream().collect(Collectors.groupingBy(TesteeExperiment::getExperimentId,Collectors.mapping(TesteeExperiment::getVpCode,Collectors.toSet())));
                            int count = 0;
                            for(Set<String> item:record1.values())
                            {
                                count += item.size();
                            }

                            complete = complete + count;
                            incomplete = incomplete + num - count;

                        }
                        FinishEntity finishEntity = new FinishEntity(complete,incomplete);
                        String statJson =  new JSONObject(finishEntity.getStat()).toString();
                        Date now = new Date();
                        StatItemResult statItemResult1 = new StatItemResult();
                        statItemResult1.setItemCode(FinishEntity.key);
                        statItemResult1.setItemName(FinishEntity.name);
                        statItemResult1.setSubjectPkId(rcode);
                        statItemResult1.setSitePkId(sitePkId);
                        statItemResult1.setStatResult(BigDecimal.valueOf(0));
                        statItemResult1.setStatJson(statJson);
                        statItemResult1.setCreateTime(now);

                        statItemResultService.remove(new LambdaQueryWrapper<StatItemResult>()
                                .eq(StatItemResult::getSubjectPkId, rcode)
                                .eq(StatItemResult::getSitePkId, sitePkId)
                                .in(StatItemResult::getItemCode, FinishEntity.key));
                        statItemResultService.saveBatch(Lists.newArrayList(statItemResult1));




                    }
            );

        });

    }


}
